package com.example.controller;

import com.example.bean.ApiResult;
import com.example.bean.User;
import com.example.service.UserService;
import com.example.utils.ApiResultHandler;
import com.example.utils.Md5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    //根据id查用户
    @GetMapping("/selectById/{userId}")
    public ApiResult selectUserById(@PathVariable int userId){
        User res = userService.selectUserById(userId);
        if (res!=null) return ApiResultHandler.buildApiResult(200,"根据用户Id查询",res);
        return ApiResultHandler.buildApiResult(400,"无此用户信息",res);
    }
    //查所有用户
    @GetMapping("/selectAll")
    public ApiResult selectUserAll(){
        List<User> res = userService.selectUserAll();
        if (res!=null) return ApiResultHandler.buildApiResult(200,"查询所有用户信息",res);
        return ApiResultHandler.buildApiResult(400,"无用户信息",res);
    }
    //添加用户
    @PostMapping("/insert")
    public ApiResult insertUser(@RequestBody User user){
        int userId = user.getUserId();
        User user1 = userService.selectUserById(userId);
        if(user1 == null){
            String password = user.getUserPassword();
            password = Md5.md5(password);   //加密
            user.setUserPassword(password);
            int res = userService.insertUser(user);
            if(res!=0)  return ApiResultHandler.buildApiResult(200,"添加用户成功",res);
            return ApiResultHandler.buildApiResult(400,"添加用户失败",res);
        }
        else return ApiResultHandler.buildApiResult(400,"此用户已存在",user1);

    }
    //删除用户
    @DeleteMapping("/delete/{userId}")
    public ApiResult deleteUser(@PathVariable int userId){
        int res = userService.deleteUser(userId);
        if(res!=0)  return ApiResultHandler.buildApiResult(200,"删除用户成功",res);
        return ApiResultHandler.buildApiResult(400,"删除用户失败",res);
    }
    //更改用户信息
    @PutMapping("/update")
    public ApiResult updateUser(@RequestBody User user){
        String password = user.getUserPassword();
        password = Md5.md5(password);   //加密
        user.setUserPassword(password);
        int res = userService.updateUser(user);
        if(res!=0)  return ApiResultHandler.buildApiResult(200,"更新用户信息成功",res);
        return ApiResultHandler.buildApiResult(400,"更新用户信息失败",res);
    }

}
